package com.hengxinguotong.zhihuichengjian.ui.lift.data;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.LiftStatistics;
import com.hengxinguotong.zhihuichengjian.bean.LiftStatisticsRes;
import com.hengxinguotong.zhihuichengjian.customtimepicker.DatePickerActivity;
import com.hengxinguotong.zhihuichengjian.customtimepicker.bean.DayTimeEntity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.view.IMarket;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link LiftDataStatisticsFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 * 统计分析
 */
public class LiftDataStatisticsFragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM = "equipmentId";

    @BindView(R.id.alarm_count_rg)
    RadioGroup alarmCountRg;
    @BindView(R.id.alarm_count_chart)
    LineChart alarmCountChart;
    @BindView(R.id.alarm_reason_rg)
    RadioGroup alarmReasonRg;
    @BindView(R.id.alarm_reason_chart)
    LineChart alarmReasonChart;
    @BindView(R.id.recycle_count_rg)
    RadioGroup recycleCountRg;
    @BindView(R.id.recycle_count_chart)
    LineChart recycleCountChart;
    @BindView(R.id.load_trend_rg)
    RadioGroup loadTrendRg;
    @BindView(R.id.load_trend_date)
    RadioButton loadTrendDate;
    @BindView(R.id.load_trend_chart)
    LineChart loadTrendChart;
    @BindView(R.id.speed_trend_rg)
    RadioGroup speedTrendRg;
    @BindView(R.id.speed_trend_date)
    RadioButton speedTrendDate;
    @BindView(R.id.speed_trend_chart)
    LineChart speedTrendChart;
    @BindView(R.id.tilt_trend_rg)
    RadioGroup tiltTrendRg;
    @BindView(R.id.tilt_trend_date)
    RadioButton tiltTrendDate;
    @BindView(R.id.tilt_trend_chart)
    LineChart tiltTrendChart;
    @BindView(R.id.height_trend_rg)
    RadioGroup heightTrendRg;
    @BindView(R.id.height_trend_date)
    RadioButton heightTrendDate;
    @BindView(R.id.height_trend_chart)
    LineChart heightTrendChart;

    // TODO: Rename and change types of parameters
    private String equipmentId;//设备id
//    private int type,//	1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
//            count;//次数，天数
//    private String time;//天，type为3,4,5,6时，count和time只传一个
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1://1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                    LiftStatistics alarmCountStatistics = (LiftStatistics) msg.obj;
                    if(alarmCountStatistics.getxData() == null || alarmCountStatistics.getxData().size() <= 0 ||
                            ((alarmCountStatistics.getWarningCountData() == null || alarmCountStatistics.getWarningCountData().size() <= 0) &&
                                    (alarmCountStatistics.getAlarmCountData() == null || alarmCountStatistics.getAlarmCountData().size() <= 0))){
                        showNoDataText(alarmCountChart);
                    }else {
                        showLineChart(alarmCountChart, alarmCountStatistics.getxData(), alarmCountStatistics.getWarningCountData(), "预警", getResources().getColor(R.color.color_FD9D00), 1);
                        addLine(alarmCountChart, alarmCountStatistics.getAlarmCountData(), "报警", getResources().getColor(R.color.color_F5573F), 1);
                    }
                    break;
                case 2://1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                    LiftStatistics alarmReasonStatistics = (LiftStatistics) msg.obj;
                    if(alarmReasonStatistics.getxData() == null || alarmReasonStatistics.getxData().size() <= 0 ||
                            ((alarmReasonStatistics.getWeightCountData() == null || alarmReasonStatistics.getWeightCountData().size() <= 0) &&
                                    (alarmReasonStatistics.getHeightCountData() == null || alarmReasonStatistics.getHeightCountData().size() <= 0) &&
                                    (alarmReasonStatistics.getSpeedCountData() == null || alarmReasonStatistics.getSpeedCountData().size() <= 0) &&
                                    (alarmReasonStatistics.getPeopleCountData() == null || alarmReasonStatistics.getPeopleCountData().size() <= 0) &&
                                    (alarmReasonStatistics.getTiltCountData() == null || alarmReasonStatistics.getTiltCountData().size() <= 0))){
                        showNoDataText(alarmReasonChart);
                    }else {
                        showLineChart(alarmReasonChart, alarmReasonStatistics.getxData(), alarmReasonStatistics.getWeightCountData(), "重量", getResources().getColor(R.color.color_AB4ECD), 2);
                        addLine(alarmReasonChart, alarmReasonStatistics.getHeightCountData(), "高度（冲顶）", getResources().getColor(R.color.color_0DB779), 2);
                        addLine(alarmReasonChart, alarmReasonStatistics.getSpeedCountData(), "速度", getResources().getColor(R.color.color_4A90E2), 2);
//                        addLine(alarmReasonChart, alarmReasonStatistics.getPeopleCountData(), "人数", getResources().getColor(R.color.color_F5573F), 2);
                        addLine(alarmReasonChart, alarmReasonStatistics.getTiltCountData(), "倾斜", getResources().getColor(R.color.color_FD9D00), 2);
                    }
                    break;
                case 3://1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                    LiftStatistics loadTrendStatistics = (LiftStatistics) msg.obj;
                    if(loadTrendStatistics.getxData() == null || loadTrendStatistics.getxData().size() <= 0 ||
                            loadTrendStatistics.getyData() == null || loadTrendStatistics.getyData().size() <= 0){
                        showNoDataText(loadTrendChart);
                    }else {
                        showLineChart(loadTrendChart, loadTrendStatistics.getxData(), loadTrendStatistics.getyData(), "重量", getResources().getColor(R.color.color_F5573F), 3);
                    }
                    break;
                case 4://1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                    LiftStatistics speedTrendStatistics = (LiftStatistics) msg.obj;
                    if(speedTrendStatistics.getxData() == null || speedTrendStatistics.getxData().size() <= 0 ||
                            speedTrendStatistics.getyData() == null || speedTrendStatistics.getyData().size() <= 0){
                        showNoDataText(speedTrendChart);
                    }else {
                        showLineChart(speedTrendChart, speedTrendStatistics.getxData(), speedTrendStatistics.getyData(), "速度", getResources().getColor(R.color.color_F5573F), 4);
                    }
                    break;
                case 5://1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                    LiftStatistics tiltTrendStatistics = (LiftStatistics) msg.obj;
                    if(tiltTrendStatistics.getxData() == null || tiltTrendStatistics.getxData().size() <= 0 ||
                            tiltTrendStatistics.getyData() == null || tiltTrendStatistics.getyData().size() <= 0){
                        showNoDataText(tiltTrendChart);
                    }else {
                        showLineChart(tiltTrendChart, tiltTrendStatistics.getxData(), tiltTrendStatistics.getyData(), "倾斜", getResources().getColor(R.color.color_F5573F), 4);
                    }
                    break;
                case 6://1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                    LiftStatistics heightTrendStatistics = (LiftStatistics) msg.obj;
                    if(heightTrendStatistics.getxData() == null || heightTrendStatistics.getxData().size() <= 0 ||
                            heightTrendStatistics.getyData() == null || heightTrendStatistics.getyData().size() <= 0){
                        showNoDataText(heightTrendChart);
                    }else {
                        showLineChart(heightTrendChart, heightTrendStatistics.getxData(), heightTrendStatistics.getyData(), "高度", getResources().getColor(R.color.color_F5573F), 4);
                    }
                    break;
                case 7://1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                    LiftStatistics recycleCountStatistics = (LiftStatistics) msg.obj;
                    if(recycleCountStatistics.getxData() == null || recycleCountStatistics.getxData().size() <= 0 ||
                            recycleCountStatistics.getyData() == null || recycleCountStatistics.getyData().size() <= 0){
                        showNoDataText(recycleCountChart);
                    }else {
                        showLineChart(recycleCountChart, recycleCountStatistics.getxData(), recycleCountStatistics.getyData(), "工作循环", getResources().getColor(R.color.color_F5573F), 4);
                    }
                    break;
            }
        }
    };

    /**
     * 不显示无数据的提示
     *
     * @param mChart
     */
    public static void showNoDataText(LineChart mChart) {
        mChart.clear();
        mChart.notifyDataSetChanged();
        mChart.setNoDataText("暂无数据");
//        mChart.setNoDataTextColor(Color.WHITE);
        mChart.invalidate();
    }

    public LiftDataStatisticsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param equipmentId Parameter .
     * @return A new instance of fragment LiftDataStatisticsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LiftDataStatisticsFragment newInstance(String equipmentId) {
        LiftDataStatisticsFragment fragment = new LiftDataStatisticsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM, equipmentId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            equipmentId = getArguments().getString(ARG_PARAM);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_lift_data_statistics, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();

    }

    @Override
    public void onLazyLoad() {
        initData(1, 7);
        initData(2, 7);
        initData(3, 10);
        initData(4, 10);
        initData(5, 10);
        initData(6, 10);
        initData(7, 7);
    }

    private void initView() {
        alarmCountRg.setOnCheckedChangeListener(this);
        alarmReasonRg.setOnCheckedChangeListener(this);
        recycleCountRg.setOnCheckedChangeListener(this);
        loadTrendRg.setOnCheckedChangeListener(this);
        speedTrendRg.setOnCheckedChangeListener(this);
        tiltTrendRg.setOnCheckedChangeListener(this);
        heightTrendRg.setOnCheckedChangeListener(this);

        initChart(alarmCountChart, 1);
        initChart(alarmReasonChart, 2);
        initChart(loadTrendChart, 3);
        initChart(speedTrendChart, 4);
        initChart(tiltTrendChart, 5);
        initChart(heightTrendChart, 6);
        initChart(recycleCountChart, 7);
    }

    private void initData(final int type, final int count){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getChartData("搜索中…", type, count);
            }
        }, 500);
    }

    public void getChartData(String alert, final int type, int count) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("equipmentId", equipmentId);//设备Id
            jsonObject.put("type", type);//
            jsonObject.put("count", count);
//            jsonObject.put("time", time);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/lifterAlarm/getChartData/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    LiftStatisticsRes res = gson.fromJson(json, LiftStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = type;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    private void initData(final int type, final String time){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getChartData("搜索中…", type, time);
            }
        }, 500);
    }

    public void getChartData(String alert, final int type, String time) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("equipmentId", equipmentId);//设备Id
            jsonObject.put("type", type);//
//            jsonObject.put("count", count);
            jsonObject.put("time", time);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/lifterAlarm/getChartData/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    LiftStatisticsRes res = gson.fromJson(json, LiftStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = type;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.alarm_count_seven_days://报警次数 7天
                initData(1, 7);//1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                break;
            case R.id.alarm_count_fifteen_days:
                initData(1, 15);
                break;
            case R.id.alarm_count_thirty_days:
                initData(1, 30);
                break;
            case R.id.alarm_reason_seven_days://报警原因 7天
                initData(2, 7);//1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                break;
            case R.id.alarm_reason_fifteen_days:
                initData(2, 15);
                break;
            case R.id.alarm_reason_thirty_days:
                initData(2, 30);
                break;
            case R.id.load_trend_ten_times://载重趋势 10次
                initData(3, 10);//1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                break;
            case R.id.load_trend_fifty_times:
                initData(3, 50);
                break;
            case R.id.load_trend_two_hundred_times:
                initData(3, 200);
                break;
            case R.id.load_trend_date:
//                gotoSelectDates(3);
                break;
            case R.id.speed_trend_ten_times://速度趋势 10次
                initData(4, 10);//1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                break;
            case R.id.speed_trend_fifty_times:
                initData(4, 50);
                break;
            case R.id.speed_trend_two_hundred_times:
                initData(4, 200);
                break;
            case R.id.speed_trend_date:
//                gotoSelectDates(4);
                break;
            case R.id.tilt_trend_ten_times://倾斜趋势 10次
                initData(5, 10);//1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                break;
            case R.id.tilt_trend_fifty_times:
                initData(5, 50);
                break;
            case R.id.tilt_trend_two_hundred_times:
                initData(5, 200);
                break;
            case R.id.tilt_trend_date:
//                gotoSelectDates(5);
                break;
            case R.id.height_trend_ten_times://高度趋势 10次
                initData(6, 10);//1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                break;
            case R.id.height_trend_fifty_times:
                initData(6, 50);
                break;
            case R.id.height_trend_two_hundred_times:
                initData(6, 200);
                break;
            case R.id.height_trend_date:
//                gotoSelectDates(6);
                break;
            case R.id.recycle_count_seven_days://工作循环 7天
                initData(7, 7);//1报警次数，2报警原因，3载重趋势，4速度趋势，5倾斜趋势，6高度趋势，7工作循环次数
                break;
            case R.id.recycle_count_fifteen_days:
                initData(7, 15);
                break;
            case R.id.recycle_count_thirty_days:
                initData(7, 30);
                break;
        }
    }

    @OnClick({R.id.load_trend_date, R.id.speed_trend_date, R.id.tilt_trend_date, R.id.height_trend_date})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.load_trend_date:
                gotoSelectDates(3);
                break;
            case R.id.speed_trend_date:
                gotoSelectDates(4);
                break;
            case R.id.tilt_trend_date:
                gotoSelectDates(5);
                break;
            case R.id.height_trend_date:
                gotoSelectDates(6);
                break;
        }
    }

    private void gotoSelectDates(int type){
        Intent intent = new Intent(getActivity(), DatePickerActivity.class);
        startActivityForResult(intent, type);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && data != null){
            DayTimeEntity selectDay = null;
            String time = null;
            switch (requestCode){
                case 3:
                    selectDay = (DayTimeEntity) data.getSerializableExtra("selectDay");
                    time = dateFormat(selectDay);
                    loadTrendDate.setText(time);
                    initData(3, time);
                    break;
                case 4:
                    selectDay = (DayTimeEntity) data.getSerializableExtra("selectDay");
                    time = dateFormat(selectDay);
                    speedTrendDate.setText(time);
                    initData(4, time);
                    break;
                case 5:
                    selectDay = (DayTimeEntity) data.getSerializableExtra("selectDay");
                    time = dateFormat(selectDay);
                    tiltTrendDate.setText(time);
                    initData(5, time);
                    break;
                case 6:
                    selectDay = (DayTimeEntity) data.getSerializableExtra("selectDay");
                    time = dateFormat(selectDay);
                    heightTrendDate.setText(time);
                    initData(6, time);
                    break;
            }
        }
    }

    private String dateFormat(DayTimeEntity dayTimeEntity){
        StringBuffer dateSb = new StringBuffer();
        dateSb.append(dayTimeEntity.getYear() + "-");
        if(dayTimeEntity.getMonth() > 9){
            dateSb.append(dayTimeEntity.getMonth() + "-");
        }else {
            dateSb.append( "0" + dayTimeEntity.getMonth() + "-");
        }
        if(dayTimeEntity.getDay() > 9){
            dateSb.append(dayTimeEntity.getDay());
        }else {
            dateSb.append( "0" + dayTimeEntity.getDay());
        }
        return dateSb.toString();
    }

    /**
     * 初始化图表
     */
    private void initChart(LineChart lineChart, int type) {
        /***图表设置***/
        //修改背景色
        lineChart.setBackgroundColor(Color.WHITE);
        //是否显示边界
        lineChart.setDrawBorders(false);
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        //是否可以拖动
        lineChart.setDragEnabled(true);
        //是否可以双击缩放
        lineChart.setDoubleTapToZoomEnabled(true);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置无数据状态
        lineChart.setNoDataText("无数据");
//        lineChart.setNoDataTextColor();
//        lineChart.setNoDataTextTypeface();

        //设置XY轴动画效果
        lineChart.animateY(2500);
        lineChart.animateX(1500);

        /***XY轴的设置***/
        XAxis xAxis = lineChart.getXAxis(); //X轴
        YAxis leftYAxis = lineChart.getAxisLeft();//左侧Y轴
        YAxis rightYaxis = lineChart.getAxisRight();//右侧Y轴
        xAxis.setTextSize(10f);
        leftYAxis.setTextSize(10f);
        rightYaxis.setTextSize(10f);
        //是否显示X Y轴自己的网格线
        xAxis.setDrawGridLines(false);
        rightYaxis.setDrawGridLines(false);
        leftYAxis.setDrawGridLines(false);
        //设置X Y轴网格线为虚线（实体线长度、间隔距离、偏移量：通常使用 0）
        leftYAxis.enableGridDashedLine(10f, 10f, 0f);
        //去掉右侧Y轴
        rightYaxis.setEnabled(false);
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        //设置X轴分割数量
        xAxis.setLabelCount(7,false);
        //将Y轴分为 5份
        leftYAxis.setLabelCount(5, false);
        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
        rightYaxis.setAxisMinimum(0f);
        //设置图表起点从0开始
        leftYAxis.setStartAtZero(true);

//        // 设置x轴的LimitLine，index是从0开始的
//        LimitLine xLimitLine = new LimitLine(4f,"xL 测试");
//        xLimitLine.setLineColor(Color.GREEN);
//        xLimitLine.setTextColor(Color.GREEN);
//        xAxis.addLimitLine(xLimitLine);
//
//        // 设置x轴的LimitLine
//        LimitLine yLimitLine = new LimitLine(50f,"yLimit 测试");
//        yLimitLine.setLineColor(Color.RED);
//        yLimitLine.setTextColor(Color.RED);
//        leftYAxis.addLimitLine(yLimitLine);
//        setStartAtZero(boolean enabled) : 设置为 true，则无论图表显示的是哪种类型的数据，该轴最小值总是0 。
        leftYAxis.setAxisMaximum(100f);//: 设置该轴的最大值。 如果设置了，这个值将不会是根据提供的数据计算出来的。设置最小值最大值需要搭配使用才能生效。
//        resetAxisMaxValue() : 调用此方法撤销先前设置的最大值。 通过这样做，你将再次允许轴自动计算出它的最大值。
        leftYAxis.setAxisMinimum(0f);// : 设置该轴的自定义最小值。 如果设置了，这个值将不会是根据提供的数据计算出来的。
//        resetAxisMinValue() : 调用此撤销先前设置的最小值。 通过这样做，你将再次允许轴自动计算它的最小值。设置最小值最大值需要搭配使用才能生效。

        leftYAxis.setSpaceTop(20f);//: 设置图表中的最高值的顶部间距占最高值的值的百分比（设置的百分比 = 最高柱顶部间距/最高柱的值）。默认值是10f，即10% 。
        leftYAxis.setSpaceBottom(0f);

        //设置描述信息
        Description description = new Description();
        description.setText("");
        lineChart.setDescription(description);

        /***折线图例 标签 设置***/
        Legend legend = lineChart.getLegend();//图例
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(10f);
        //显示位置 左下方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
        //是否显示图例
        switch (type){
            case 1:
            case 2:
                legend.setEnabled(true);
                break;
            case 3:
            case 4:
            case 5:
            case 6:
                xAxis.setLabelRotationAngle(-45);
                legend.setEnabled(false);
                break;
            case 7:
                legend.setEnabled(false);
                break;
        }

    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     * @param color       线条颜色
     * @param mode
     */
    private void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        //设置曲线颜色
        lineDataSet.setColor(color);
        //设置曲线圆点颜色
        lineDataSet.setCircleColor(color);
        //设置曲线宽度
        lineDataSet.setLineWidth(1f);
        //设置曲线圆点半径
        lineDataSet.setCircleRadius(1.5f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(true);
        //设置曲线节点值字体大小
        lineDataSet.setValueTextSize(10f);
        //设置折线图填充
        lineDataSet.setDrawFilled(false);
        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15.f);
        if (mode == null) {
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        } else {
            lineDataSet.setMode(mode);
        }
    }

    /**
     * 展示曲线
     *
     * @param xData x轴数据集合
     * @param yData y轴数据集合
     * @param name     曲线名称
     * @param color    曲线颜色
     * @param type    表格类型
     */
    public void showLineChart(LineChart lineChart, final List<String> xData, List<Float> yData, String name, int color, final int type) {
        YAxis leftYAxis = lineChart.getAxisLeft();
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < yData.size(); i++) {
            float data = yData.get(i);
            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */
            Entry entry = new Entry(i, data);
            entries.add(entry);
            if(data > 0){
                leftYAxis.resetAxisMaximum();//调用此方法撤销先前设置的最大值。 通过这样做，你将再次允许轴自动计算出它的最大值。
            }
        }
        //自定义x轴显示内容
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String tradeDate = xData.get((int) value % xData.size());
                return tradeDate;
            }
        });
        //自定义y轴显示内容
//        YAxis leftYAxis = lineChart.getAxisLeft();
//        leftYAxis.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//                return value + "";
//            }
//        });
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        //LINEAR 折线图  CUBIC_BEZIER 圆滑曲线
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        //线条自定义内容 放在这里
        lineDataSet.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return value + "";
            }
        });
        LineData lineData = new LineData(lineDataSet);
        //设置是否显示节点值
        lineData.setDrawValues(false);
        lineChart.setData(lineData);

        //设置节点点击悬浮窗
        final IMarket iMarket = new IMarket();
        lineChart.setMarker(iMarket);
        lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
            }

            @Override
            public void onNothingSelected() {}
        });

        lineChart.notifyDataSetChanged();
        lineChart.invalidate();
    }

    /**
     * 添加曲线
     */
    private void addLine(LineChart lineChart, List<Float> yData, String name, int color, final int type) {
        YAxis leftYAxis = lineChart.getAxisLeft();
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < yData.size(); i++) {
            float data = yData.get(i);
            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */
            Entry entry = new Entry(i, data);
            entries.add(entry);
            if(data > 0){
                leftYAxis.resetAxisMaximum();//调用此方法撤销先前设置的最大值。 通过这样做，你将再次允许轴自动计算出它的最大值。
            }
        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        //线条自定义内容 放在这里
        lineDataSet.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return value + "";
            }
        });
        LineData lineData = lineChart.getLineData();
        lineData.addDataSet(lineDataSet);

        //设置是否显示节点值
        lineData.setDrawValues(false);
        lineChart.setData(lineData);

        //设置节点点击悬浮窗
        final IMarket iMarket = new IMarket();
        lineChart.setMarker(iMarket);
        lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
            }

            @Override
            public void onNothingSelected() {}
        });

        lineChart.notifyDataSetChanged();

        lineChart.invalidate();
    }

}
